// Copyright 2022 The Goploy Authors. All rights reserved.
// Use of this source code is governed by a GPLv3-style
// license that can be found in the LICENSE file.

package model

import sq "github.com/Masterminds/squirrel"

const serverAgentTable = "`server_agent`"

type ServerAgent struct {
	ID         int64  `json:"id"`
	ServerID   int64  `json:"serverId"`
	AgentIp    string `json:"agentIp"`
	AgentPort  uint8  `json:"agentPort"`
	InsertTime string `json:"insertTime,omitempty"`
	UpdateTime string `json:"updateTime,omitempty"`
}

type ServerAgents []ServerAgent

func (c ServerAgent) GetServerAgentByServerId() (ServerAgent, error) {
	var serverAgent ServerAgent
	err := sq.
		Select(
			"id",
			"server_id",
			"agentIp",
			"agentPort",
			"insert_time",
			"update_time",
		).
		From(serverAgentTable).
		Where(sq.Eq{"server_id": c.ServerID}).
		RunWith(DB).
		QueryRow().Scan(
		&serverAgent.ID,
		&serverAgent.ServerID,
		&serverAgent.AgentIp,
		&serverAgent.AgentPort,
		&serverAgent.InsertTime,
		&serverAgent.UpdateTime,
	)
	if err != nil {
		return serverAgent, err
	}
	return serverAgent, nil
}

func (c ServerAgent) AddRow() (int64, error) {
	result, err := sq.
		Insert(serverAgentTable).
		Columns(
			"server_id",
			"expression",
			"command",
			"single_mode",
			"log_level",
			"description",
			"creator",
		).
		Values(
			c.ServerID,
			c.AgentIp,
			c.AgentIp,
			c.InsertTime,
		).
		RunWith(DB).
		Exec()
	if err != nil {
		return 0, err
	}
	id, err := result.LastInsertId()
	return id, err
}

func (c ServerAgent) RemoveRow() error {
	_, err := sq.
		Update(serverAgentTable).
		Where(sq.Eq{"id": c.ID}).
		RunWith(DB).
		Exec()
	return err
}
